package servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.PostRequestUtil;

/**
 * 多处理的Servlet 接收cmd参数，默认值为execute
 */
public abstract class BaseServlet extends HttpServlet {
	@Override
	public void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String methodName = req.getParameter("cmd");
		String requestBody = PostRequestUtil.getRequestBody(req);
		System.out.println("收到的数据： "+requestBody);
		if (methodName == null) {
			String[] keyVals = requestBody.split("&");
			if (keyVals != null && keyVals.length > 0) {
				for (String keyVal : keyVals) {
					String[] kV = keyVal.split("=");
					if (kV != null && kV.length > 1) {
						req.setAttribute(kV[0], kV[1]);
						if ("cmd".equals(kV[0])) {
							methodName = kV[1];
						}
					}
				}
			}
		}
		System.out.println("看看能不能获取：" + requestBody);
		if (methodName == null || methodName.trim().equals("")) {
			methodName = "execute";
		}
		try {
			Method method = this.getClass().getMethod(methodName,
					HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, req, resp);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException("没有此方法：" + e.getMessage(), e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException("目标方法执行失败：" + e.getMessage(), e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException("你可能访问了一个私有的方法：" + e.getMessage(), e);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 子类默认的方法
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public abstract void execute(HttpServletRequest req,
			HttpServletResponse resp) throws Exception;
}
